package fr.xebia.monitoring.appender;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import fr.xebia.monitoring.Monitor;
import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.Measure;
import fr.xebia.monitoring.config.MeasureType;

/**
 * Default category for logger is {@link Monitor} and default logging level is {@link Level.TRACE}
 */
public class Log4jAppender extends AbstractMeasureAppender {

	private Logger appendLogger = Logger.getLogger(Monitor.class);
	private Level level = Level.TRACE;
	
	@Override
	public void run() {
		if (appendLogger.isEnabledFor(level)) {
			String formatedMeasures = null;
			if (getMeasureType().equals(MeasureType.AGGREGATED)) {
				logger.debug("Appending aggregated measures");
				AggregatedMeasures agregatedMeasures = getAggregatedMeasures();
				formatedMeasures = getFormater().format(agregatedMeasures);
			} else {
				logger.debug("Appending raw measures");
				Measure[] measures = getMeasures();
				formatedMeasures = getFormater().format(measures);
			}
			appendLogger.log(level, formatedMeasures);
		}
	}

	public void setCategoryName(String categoryName) {
		this.appendLogger = Logger.getLogger(categoryName);
	}

	public void setLevel(String level) {
		this.level = Level.toLevel(level);
	}
}
